package com.shushan.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.shushan.base.Constants;
import com.shushan.shushanbao.R;
import com.shushan.util.SharedPreferencesUtils;

/**
 * @ClassName: PlayerMusicService
 * @Desciption: 循环播放一段无声音频，以提升进程优先级
 * @author: yichaohua
 * @date: 2018-05-25
 */
public class PlayerMusicService extends Service {

    private final static String TAG = "PlayerMusicService";
    private MediaPlayer mMediaPlayer;

    private BroadcastReceiver stopSelfReceiver = new BroadcastReceiver(){

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(TAG,"onReceive()");
            stopSelf();
        }
    };

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        Log.d(TAG,TAG+"---->onCreate,启动服务");

        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(Constants.STOP_PLAY_RECEIVER_ACTION);
        registerReceiver(stopSelfReceiver, mFilter);

        mMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.silent);
        mMediaPlayer.setLooping(true);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                startPlayMusic();
            }
        }).start();
        return START_STICKY;
    }

    private void startPlayMusic(){
        if(mMediaPlayer != null){

            Log.d(TAG,"启动后台播放音乐");

            mMediaPlayer.start();
        }
    }

    private void stopPlayMusic(){
        if(mMediaPlayer != null){
            Log.d(TAG,"关闭后台播放音乐");

            mMediaPlayer.stop();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if(stopSelfReceiver != null){
            unregisterReceiver(stopSelfReceiver);
        }

        stopPlayMusic();

        boolean isChildControl = SharedPreferencesUtils.getBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);
        Log.i(TAG,"onDestroy() isChildControl=" + isChildControl);
        if(isChildControl){
            // 重启自己
            Intent intent = new Intent(getApplicationContext(),PlayerMusicService.class);
            startService(intent);
        }

    }
}
